package com.apes.autoparts.supplier.inheart;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.supplier.platform.*;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.mq.MQUtil;
import com.apes.framework.util.MapUtil;
import org.elasticsearch.index.IndexNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * Created by lishikun on 2021/4/19 15:57
 */
public class InHeartApi<T, R> extends SupplierPlatformApi<T, R> {

    @Autowired
    SupplierPlatformRepository supplierPlatformRepository;
    @Autowired
    InHeartRepository inHeartRepository;

    private SupplierPlatform supplierPlatform;
    // 初始化
    InHeartApi() {
        this.source = SupplierPlatformConst.IN_HEART;
    }
    //
    private SupplierPlatform getSupplierPlatform() {
        if (this.supplierPlatform != null) return this.supplierPlatform;

        SupplierPlatform supplierPlatform = SpringManager.getBean(SupplierPlatformRepository.class).findOne(
                JpaDsl.toCriteriaByEq(
                        "code", getSource()
                )
        ).orElse(null);
        if (supplierPlatform == null) throw new RuntimeException("未找到当前平台：" + getSource());
        this.supplierPlatform = supplierPlatform;
        return this.supplierPlatform;
    }
    /***
     * 1. 先获取库存基本信息
     * 2. 获取库存详细信息
     * 3. 区分库存信息类型， 新增，修改，还是重要属性发生改变
     * 4. 批量处理新增，修改，重要属性修改和
     * @param supplierPlatformItem
     */
    @Override
    public void synTotal(SupplierPlatformItem supplierPlatformItem) {
        JSONObject allkcKey = getAllkcKey(supplierPlatformItem);
//        JSONObject allkcKey = new JSONObject();
//        allkcKey.put("dcount", 22424);
//        allkcKey.put("pcount", 45);
//        allkcKey.put("allkckey", "9e2935bf40e5ab9de7f7a586bd34d73c");
        if (supplierPlatformItem.getState().equals("debugging")) {
            delete(supplierPlatformItem);
        }
        int pcount = allkcKey.getIntValue("pcount");
        for (int i = 1; i <= pcount; i++) {
            JSONObject allkc = getAllKc(supplierPlatformItem, allkcKey, i);
            if (i == pcount) allkc.put("lastData", true);
            handHeap(allkc, supplierPlatformItem, "synTlotal");
        }
    }

    @Override
    public void synIncrement(SupplierPlatformItem supplierPlatformItem) {
        JSONObject changeKc = getChangeKc(supplierPlatformItem, 1);
        handHeap(changeKc, supplierPlatformItem, "synIncrement");
    }

    @Override
    public R getProductStock(SimpleRequest request) {
        return null;
    }

    /***
     * 测试
     * @param supplierPlatformItem
     */
    @Override
    public void test(SupplierPlatformItem supplierPlatformItem) {

    }

    @Override
    public void simulationApi(SupplierPlatformItem supplierPlatformItem, JSONObject jo) {

    }

    @Override
    public List<Map> getRowData(SupplierPlatformItem supplierPlatformItem, String source) {
        return null;
    }

    @Override
    public void handleRow(SimpleRequest request) {

    }



    /***
     * 登录所有库存参数 allkckey 密钥，pcount 库存总批数， dcount 所有库存总条数
     */
    public JSONObject getAllkcKey(SupplierPlatformItem supplierPlatformItem) {
        String url = getSupplierPlatform().getUrl() + "?psign=" + getSupplierPlatform().getAppKey() +
                "&gsign=" + supplierPlatformItem.getAccessKey() + "&mode=allkckey";
        return resolveError(requestCore(url, MapUtil.mapper(), null));
    }

    /***
     * 获取所有的库存
     * http://api.inheartsoft.com/dw-api/kc2018?psign=PSIGN&gsign=GSIGN&mode=all_kc&allkckey=ALLKCKEY&pindex=1
     */
    public JSONObject getAllKc(SupplierPlatformItem supplierPlatformItem, JSONObject allkcKey, int pindex) {
        String url = getSupplierPlatform().getUrl() + "?psign=" + getSupplierPlatform().getAppKey() +
                "&gsign=" + supplierPlatformItem.getAccessKey() +
                "&mode=all_kc&allkckey=" + allkcKey.getString("allkckey") +
                "&pindex=" + pindex;
        return resolveError(requestCore(url, MapUtil.mapper(), null));
    }

    /***
     * 获取变化的库存
     * http://api.inheartsoft.com/dw-api/kc2018?psign=PSIGN&gsign=GSIGN&mode=change_kc&isauto=1
     */
    public JSONObject getChangeKc(SupplierPlatformItem supplierPlatformItem, int isauto) {
        String url = getSupplierPlatform().getUrl() + "?psign=" + getSupplierPlatform().getAppKey() +
                "&gsign=" + supplierPlatformItem.getAccessKey() +
                "&mode=change_kc&isauto=" + isauto;
        return resolveError(requestCore(url, MapUtil.mapper(), null));
    }

    /***
     * 更新标记变化库存
     * http://api.inheartsoft.com/dw-api/kc2018?psign=PSIGN&gsign=GSIGN&mode=change_kc&isauto=1
     */
    public JSONObject changeSign(SupplierPlatformItem supplierPlatformItem, String change_sign) {
        String url = getSupplierPlatform().getUrl() + "?psign=" + getSupplierPlatform().getAppKey() +
                "&gsign=" + supplierPlatformItem.getAccessKey() +
                "&mode=change_sign&change_sign=" + change_sign;
        return resolveError(requestCore(url, MapUtil.mapper(), null));
    }
    /***
     * 处理返回值
     */
    private JSONObject resolveError(JSONObject param) {

        if (param.getIntValue("msgcode") != 0 ) {
            if ("allkckey".equals(param.getString("mode")))
                throw new RuntimeException(param.getString("msgtext"));
        }
        return param;
    }

    private void handHeap(JSONObject allkc, SupplierPlatformItem supplierPlatformItem , String action) {
        int size = allkc.getIntValue("size");
        JSONArray list = allkc.getJSONArray("list");
        if (list == null) return;
        JSONObject jo = new JSONObject();
        jo.put("supplierPlatformItemId", supplierPlatformItem.getId());
        for (int i = 0; i <= size / 1000; i++) {
            List subList =  (List)list.subList(i * 1000, i != (size / 1000 ) ? (i + 1) * 1000 : size);
            jo.put("data", subList);
            jo.put("action", action);
            if (i == size/1000) jo.put("lastData", true);
//            SimpleRequest request = new SimpleRequest();
//            request.setData(jo);
//            SpringManager.getBean(InHeartService.class).handHeap(request);
            // 切片处理数据防止数据量过大造成堵塞
            String topic ;
            if (supplierPlatformItem.getState().equals("debugging")) {
                topic = "auto.inHeart.debugging";
            } else {
                topic = "auto.inHeart.handHeap";
            }
            MQUtil.publish(topic, "用心接口数据", jo);
        }
    }
    public void delete(SupplierPlatformItem supplierPlatformItem) {
        try {
            SpringManager.getBean(InHeartDebugRepository.class).deleteBySupplierPlatformItem(supplierPlatformItem.getId());
        } catch (IndexNotFoundException e) {
            e.printStackTrace();
        }
    }
}
